import axios from 'axios';
import { Message } from 'element-ui';
import router from '../router/index'
import Vue from 'vue';
axios.defaults.baseURL = 'http://localhost:3031/api';
Vue.prototype.axios = axios;
// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading;
function startLoading() {
  loading = Vue.prototype.$loading({
    lock: true,
    text: "Loading...",
    target: document.querySelector('.loading-area')//设置加载动画区域
  });
}
function endLoading() {
  loading.close();
}
 
//声明一个对象用于存储请求个数
let needLoadingRequestCount = 0;
function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading();
    }
    needLoadingRequestCount++;
};
function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return;
    needLoadingRequestCount--;
    if (needLoadingRequestCount === 0) {
      endLoading();
    }
};
 
//  请求拦截
axios.interceptors.request.use(config => {
  showFullScreenLoading();
  return config;
}, err => {
  tryHideFullScreenLoading();
  Message.error({ message: '请求超时!' });
  return Promise.resolve(err);
})
//  响应拦截
axios.interceptors.response.use(res => {
  tryHideFullScreenLoading();
  if (res.data.code == 200) {
    return res.data.result;
  } else if (res.data.code == 401) {
    router.push('/login');
    return Promise.reject(res);
  } else if (res.data.code == 201) {
    Message.error({ message: res.data.msg });
    return Promise.reject(res);
  }
  return Promise.reject(res);
}, err => {
  tryHideFullScreenLoading();
  if (err.response.status == 504 || err.response.status == 404) {
    Message.error({ message: '服务器被吃了⊙﹏⊙∥' });
  } else if (err.response.status == 403) {
    Message.error({ message: '权限不足,请联系管理员!' });
  } else {
    Message.error({ message: '未知错误' });
  }
  return Promise.reject(err);
})
 
let base = '';
export const postRequest = (url, params) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: params,
    transformRequest: [function (data) {
      let ret = ''
      for (let it in data) {
        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
      }
      return ret
    }],
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
}
export const getRequest = (url, data = '') => {
  return axios({
    method: 'get',
    params: data,
    url: `${base}${url}`
  });
}